問題十三 Go 讀寫檔案時常犯的錯誤
我之前再打工的時候撰寫 Go 語言的時候,我在讀取、寫入檔案的時候有注意到一個問題,如果你正常的讀取檔案像下面這樣
file, err := os.Open("test.csv") // For read access.
if err != nil {
log.Fatal(err)
}
businessFile, err := os.Create("business.txt")
companyFile, err := os.Create("company.txt")
subCompanyFile, err := os.Create("subcompany.txt")
//br := bufio.NewReader(file)
br := bufio.NewScanner(file)
writeBusiness := bufio.NewWriter(businessFile)
writeCompany := bufio.NewWriter(companyFile)
writeSubCompany := bufio.NewWriter(subCompanyFile)
for br.Scan() {
if err != nil {
break
}
line := br.Text()
stringSlice := strings.Split(line, ",")
if stringSlice[1] == "商業登記" {
writeBusiness.WriteString(line + "\n")
} else if stringSlice[1] == "公司" {
writeCompany.WriteString(line + "\n")
} else if stringSlice[1] == "分公司" {
writeSubCompany.WriteString(line + "\n")
}
fmt.Printf("%v\n", line)
}
if err := br.Err(); err != nil {
log.Fatal(err)
}
這個 Code 看起來很正常,正常的讀取寫入檔案,如果檔案很小大概都沒有問題,但是檔案一大就會發現寫入後的結果不對,會少一些字又或是亂碼,這個是因為沒有 flush 掉舊的記憶體的關係。
所以下面這個才是對的
file, err := os.Open("test.csv") // For read access.
if err != nil {
log.Fatal(err)
}
//dataStruct := map[string]string{}
businessFile, err := os.Create("business.txt")
companyFile, err := os.Create("company.txt")
subCompanyFile, err := os.Create("subcompany.txt")
//br := bufio.NewReader(file)
br := bufio.NewScanner(file)
writeBusiness := bufio.NewWriter(businessFile)
writeCompany := bufio.NewWriter(companyFile)
writeSubCompany := bufio.NewWriter(subCompanyFile)
for br.Scan() {
//line, err := br.ReadString('\n')
if err != nil {
break
}
//stringSlice []string
line := br.Text()
stringSlice := strings.Split(line, ",")
//fmt.Printf("%#v\n", stringSlice)
if stringSlice[1] == "商業登記" {
writeBusiness.WriteString(line + "\n")
writeBusiness.Flush()
} else if stringSlice[1] == "公司" {
writeCompany.WriteString(line + "\n")
writeCompany.Flush()
} else if stringSlice[1] == "分公司" {
writeSubCompany.WriteString(line + "\n")
writeSubCompany.Flush()
}
fmt.Printf("%v\n", line)
}
if err := br.Err(); err != nil {
log.Fatal(err)
}
寫入後 flush 掉就 ok 了